import { Card, Table, message, Spin } from 'antd';
import type { TablePaginationConfig } from 'antd/es/table';
import React, { useState, useEffect } from 'react';
import { listMaterialPageUsingPost } from '@/services/weixin/wxMpMaterialController';
import MaterialQueryRequest = API.MaterialQueryRequest;

// 标签配置
const tabList = [
  { key: 'image', tab: '图片' },
  { key: 'voice', tab: '音频' },
  { key: 'video', tab: '视频' }
];

// 类型映射中文
const typeNameMap: Record<string, string> = {
  image: '图片',
  voice: '音频',
  video: '视频'
};

const App: React.FC = () => {
  // 标签状态
  const [activeTabKey1, setActiveTabKey1] = useState<string>('image');

  // 数据相关状态
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<API.BaseResponse>();
  const [queryParams, setQueryParams] = useState<MaterialQueryRequest>({
    current: 1,
    pageSize: 10,
    type: 'image' // 初始类型与标签状态一致
  });

  // 列定义
  const columns = [
    { title: '素材名称', dataIndex: 'name', width: 200 },
    {
      title: '内容预览',
      render: (record: any) => {
        switch (activeTabKey1) {
          case 'image':
            return <img src={record.url} style={{ width: 60, height: 60 }} />;
          case 'voice':
            return <audio src={record.url} controls />;
          case 'video':
            return <video src={record.url} controls style={{ width: 200 }} />;
          default:
            return null;
        }
      }
    },
    { title: '上传时间', dataIndex: 'createTime', width: 180 }
  ];

  // 数据获取
  const fetchData = async () => {
    setLoading(true);
    try {
      const response = await listMaterialPageUsingPost(queryParams);
      if (response.code === 200) {
        setData(response.data);
      } else {
        message.error(response.message || '加载失败');
      }
    } catch (error) {
      message.error('请求异常');
      console.error('API Error:', error);
    } finally {
      setLoading(false);
    }
  };

  // 监听参数变化自动加载
  useEffect(() => {
    fetchData();
  }, [queryParams]);

  // 处理标签切换
  const handleTabChange = (key: string) => {
    setActiveTabKey1(key);
    setQueryParams(prev => ({
      ...prev,
      type: key,
      current: 1 // 切换分类重置页码
    }));
  };

  // 处理分页变化
  const handleTableChange = (pagination: TablePaginationConfig) => {
    setQueryParams(prev => ({
      ...prev,
      current: pagination.current,
      pageSize: pagination.pageSize
    }));
  };

  return (
    <Card
      style={{ width: '100%' }}
      title="素材库"
      tabList={tabList}
      activeTabKey={activeTabKey1}
      onTabChange={handleTabChange}
    >
      <Spin spinning={loading}>
        <div style={{ marginBottom: 16 }}>
          <h3>{typeNameMap[activeTabKey1]}列表</h3>
        </div>

        <Table
          columns={columns}
          dataSource={data?.records || []}
          rowKey="id"
          pagination={{
            current: queryParams.current,
            pageSize: queryParams.pageSize,
            total: data?.total || 0,
            showSizeChanger: true,
            showTotal: total => `共 ${total} 条`
          }}
          onChange={handleTableChange}
          scroll={{ x: 800 }}
        />
      </Spin>
    </Card>
  );
};

export default App;
